var app = getApp();
Page({
  data: {
    msg: '加载中...',
    storeid: 0
  },
  onShow: function () {
    setTimeout(() => {
      if (app.config.MOCK.STATUS) {
        setTimeout(() => {
          wx.switchTab({
            url: app.config.PAGE.HOME + '?name=商城',
          })
        }, 1000)
        return;
      }

      app.security.isAuthenticated().then(() => {
        this.getStoreInfo(this.data.storeid);
      }, () => {
        this.login(this.data.storeid);
      })
    }, 500);
  },
  onLoad: function (options) {
    // wx.checkSession({
    //   success: function () {
    //     console.log('登录态未过期')
    //   },
    //   fail: function () {
    //     console.log('登录态过期')
    //   }
    // })

    this.setData({
      storeid: wx.getStorageSync(app.config.CACHE.STOREID)
    })

    if (options.productid) {
      wx.setStorageSync(app.config.SHARE.PAGE, app.config.PAGE.PRODUCT + '?id=' + options.productid)
    }
    if (options.grouppurchaseid) {
      wx.setStorageSync(app.config.SHARE.PAGE, app.config.PAGE.GROUPPURCHASE + '?id=' + options.grouppurchaseid)
    }
    if (options.orderid) {
      wx.setStorageSync(app.config.SHARE.PAGE, '/package/order/pages/order/order?id=' + options.orderid)
    }
    if (options.categoryid) {
      if (options.categoryid != 0) {
        wx.setStorageSync(app.config.CACHE.CATEGORYID, options.categoryid)
      }
      wx.setStorageSync(app.config.SHARE.PAGE, 'category')
    }
    if (options.bargaingoodid) {
      let sharepage = '/package/activity/pages/bargain/bargain?id=' + options.bargaingoodid;
      if (options.bargainid) {
        sharepage += '&bargainid=' + options.bargainid
      }
      wx.setStorageSync(app.config.SHARE.PAGE, sharepage);
    }
    if (options.page == 'off' || options.page == 'limits' || options.page == 'bargains') {
      wx.setStorageSync(app.config.SHARE.PAGE, (app.config.SHARE.PAGES[options.page]) + (options.title ? '?title=' + options.title : ''))
    }
    if (options.page) {
      wx.setStorageSync(app.config.SHARE.PAGE, app.config.SHARE.PAGES[options.page])
    }
  },
  login: function (storeid) {
    wx.login({
      success: (res) => {
        app.http.get('/auth/applet/jscode2session?code=' + res.code + '&store_id=' + storeid).then((ress) => {
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: (userinfo) => {
              let data = {
                "encrypted_data": userinfo.encryptedData,
                "iv": userinfo.iv,
                "open_id": ress.open_id,
                "store_id": storeid
              }
              if (wx.getStorageSync(app.config.CACHE.SHAREID)) {
                data.user_id = wx.getStorageSync(app.config.CACHE.SHAREID);
              }
              app.http.post('/auth/applet/login', data).then((res) => {
                app.security.setUserId(res.user_id)
                app.security.setToken({
                  value: res.access_token,
                  expire: Number(res.access_token_expired_time)
                })
                app.security.setRefreshToken({
                  value: res.refresh_token,
                  expire: Number(res.refresh_token_expired_time)
                })

                this.getStoreInfo(storeid);
              }, (msg) => {
                this.handleError(msg)
              })
            },
            fail: (error) => {
              if (error.errMsg == 'getUserInfo:fail auth deny') {
                app.wxapp.auth('无法获取用户信息，请开启允许获取用户信息')
              } else {
                this.handleError(error.errMsg)
              }
            }
          })
        }, (msg) => {
          this.handleError(msg)
        })
      },
      fail: (res) => {
        this.handleError(res.errMsg || 'wx.login fail')
      }
    })
  },
  getStoreInfo: function (storeid) {
    app.security.http('get', '/store/' + storeid + '/info').then((store) => {
      wx.setStorageSync(app.config.CACHE.STORE, store)
      app.config.SHARE.TITLE = store.name;
      app.getHomeConfig().then(() => {
        wx.switchTab({
          url: app.config.PAGE.HOME,
        })
      })
    }, (msg) => {
      this.handleError(msg)
    })
  },
  handleError: function (msg) {
    wx.navigateTo({
      url: app.config.PAGE.ERROR + '?msg=' + msg,
    })
  }
})
